package com.hencoder.hencoderpracticedraw1.practice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.hencoder.hencoderpracticedraw1.Data;

import java.util.ArrayList;
import java.util.List;

public class Practice10HistogramView extends View {

    private static final String NAME = "直方图";
    private Paint paint;
    private Path path;
    private final List<Data> dataList = new ArrayList<>();
    private int horizontalSpace = 10;
    private int squareWidth = 80;

    public Practice10HistogramView(Context context) {
        super(context);
        init();
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.WHITE);
        paint.setTextSize(50);
        path = new Path();

        dataList.add(new Data("Froyo", 10, "#72B916"));
        dataList.add(new Data("ICS", 20, "#72B916"));
        dataList.add(new Data("JB", 20, "#72B916"));
        dataList.add(new Data("KK", 40, "#72B916"));
        dataList.add(new Data("L", 80, "#72B916"));
        dataList.add(new Data("M", 90, "#72B916"));
        dataList.add(new Data("N", 30, "#72B916"));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        综合练习
//        练习内容：使用各种 Canvas.drawXXX() 方法画直方图
        //画坐标轴
        path.moveTo(200, 50);
        path.rLineTo(0, 550);
        path.rLineTo(700, 0);
        canvas.drawPath(path, paint);

        //画文字 直方图
        float x = canvas.getWidth() / 2 - paint.measureText(NAME) / 2, y = 750;
        canvas.drawText(NAME, x, y, paint);

        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(20);
        float left = 200 + horizontalSpace;
        float top = 0;
        float right = left + squareWidth;
        float bottom = 600;
        for (Data data : dataList) {
            //画方块
            paint.setColor(Color.parseColor(data.getColor()));
            top = (float) (bottom - data.getNumber() / 100.0 * 600.0);
            canvas.drawRect(left, top, right, bottom, paint);
            //画对应的文本
            paint.setColor(Color.WHITE);
            String name = data.getName();
            float textX = right - squareWidth / 2 - paint.measureText(name) / 2;
            canvas.drawText(name, textX, bottom + 40, paint);

            left = right + horizontalSpace;
            right = left + squareWidth;
        }

    }

}
